<template>
  <div class="uploader">
    <file-upload
      v-show="false"
      class="btn btn-primary dropdown-toggle"
      :post-action="postAction"
      extensions="gif,jpg,jpeg,png,webp"
      accept="image/png,image/gif,image/jpeg,image/webp"
      :multiple="true"
      :directory="chooseDirectory"
      :thread="3"
      :drop="!started"
      :drop-directory="true"
      v-model="files"
      input-id="select-file"
      @input-file="inputFile"
      @input-filter="inputFilter"
      ref="upload">
      <i class="material-icons">image</i>
    </file-upload>
    <div class="file-list" v-show="files.length">
      <table class="table files">
        <thead>
          <tr>
            <th scope="col">#</th>
            <th scope="col">Name</th>
            <th scope="col">Size</th>
            <th scope="col">Progress</th>
            <th scope="col">Operation</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(file, index) of files">
            <td class="align-middle">
              <div class="d-inline-block" :class="{'text-info': file.active, 'text-success': file.success, 'text-danger': file.error}">
                <i class="material-icons d-inline-block align-middle">image</i><span>{{file.type}}</span>
              </div>

              
            </td>
            <td class="align-middle">
              <input class="form-control file-name-editor" type="text" v-model="file.name" :disabled="file.active || file.success">
            </td>
            
            <td class="align-middle">{{formateSize(file.size)}}</td>
            <td class="align-middle">
              <div class="progress-container">
                <div :class="{'bg-info': !file.error, 'bg-danger': file.error}" :style="{width: file.progress + '%'}"></div>
              </div>
            </td>
            <td class="align-middle text-center">
              <i class="material-icons text-danger d-inline-block btn" data-toggle="tooltip" data-placement="top" title="取消" v-tooltip @click.prevent="$refs.upload.remove(file.id)" v-if="!started" key="item-close">close</i>
              <i class="material-icons text-danger d-inline-block btn" data-toggle="tooltip" data-placement="top" title="中止" v-tooltip @click.prevent="$refs.upload.update(file, {active: false, error: 'stop'})" v-else-if="file.active" key="item-stop">stop</i>
              <i class="material-icons text-danger d-inline-block btn" data-toggle="tooltip" data-placement="top" title="重试" v-tooltip @click.prevent="$refs.upload.update(file, {active: true, error: '', progress: '0.00'})" v-else-if="file.error" key="item-update">update</i>
              <i class="material-icons text-success d-inline-block btn" data-toggle="tooltip" data-placement="top" title="完成" v-tooltip v-else-if="file.success" key="item-done">done</i>
            </td>
          </tr>
        </tbody>
      </table>
      
    </div>
    <div class="drop-tip" :class="{'full': files.length, 'bg-info': $refs.upload ? !$refs.upload.dropActive : true, 'bg-secondary': $refs.upload ? $refs.upload.dropActive : false}" v-if="!files.length || $refs.upload.dropActive">
      
    </div>

    <div class="d-flex justify-content-end">
      <label for="select-file" class="m-2 btn btn-outline-info btn-sm" @mousedown="chooseDirectory=true;" v-if="!started">选择文件夹</label>
      <label for="select-file" class="mr-auto m-2 btn btn-outline-info btn-sm" @mousedown="chooseDirectory=false;" v-if="!started">选择文件</label>

      <button class="btn btn-danger  btn-sm m-2" @click="$refs.upload.clear()" v-if="files.length && !started">清空</button>

      <button class="btn btn-success btn-sm m-2" @click="close" v-if="done">完成</button>
      <button class="btn btn-primary btn-sm m-2" @click="retry" v-else-if="retried">重试</button>
      <button class="btn btn-danger btn-sm m-2" @click="stop" v-else-if="uploading">中止</button>
      

      <button class="btn btn-primary btn-sm m-2" @click="start" v-if="!started">确定</button>
      <button class="btn btn-outline-dark btn-sm m-2" @click="close" :disabled="uploading" v-if="!done">关闭</button>
    </div>
  </div>
</template>
<style>

</style>

<script>
import Scrollbar from 'smooth-scrollbar'
import FileUpload from 'vue-upload-component'
export default {
  components: {
    FileUpload,
  },
  props: {
    postAction: {
      type: String,
      default: "/model/image/create"
    },
    directory: {
      type: String,
      required: true,
    },
    callback: {
      type: Function,
      default: function(arr) {
        // console.log('success files: ', arr, arr.length);
      }
    }
  },

  data() {
    return {
      files: [],
      successCount: 0,
      uploading: false,
      started: false,
      chooseDirectory: false,
    }
  },
  computed: {
    retried() {
      return this.started ? !this.uploading && this.successCount != this.files.length : false;
    },
    done() {
      return this.started ? this.successCount == this.files.length : false;
    }
  },
  methods: {
    start() {
      if (this.started || !this.files.length) {
        return;
      }
      this.started = true;
      this.successCount = 0;
      this.$refs.upload.active = true;
    },
    retry() {
      var vm = this;
      vm.files.forEach(function(file) {
        if (!file.active && !file.success && file.error) {
          vm.$refs.upload.update(file, {active: false, progress: 0, error: ''});
        }
      })
      vm.$refs.upload.active = true;
    },
    stop() {
      var vm = this;
      vm.$refs.upload.active = false;
    },
    inputFilter(newFile, oldFile, prevent) {
      if (newFile && !oldFile) {
        // Before adding a file
        // 添加文件前
        // Filter system files or hide files
        // 过滤系统文件 和隐藏文件
        // console.log('here');
        if (/(\/|^)(Thumbs\.db|desktop\.ini|\..+)$/.test(newFile.name)) {
          return prevent()
        }
        // Filter php html js file
        // 过滤 php html js 文件
        if (/\.(php5?|html?|jsx?)$/i.test(newFile.name)) {
          return prevent()
        }

        if (!/^image/i.test(newFile.type)) {
          return prevent()
        }
        newFile.name = newFile.name.replace(/.*\//, '');
      } else {
        if (newFile && oldFile) {
          var ext = newFile.type.split('/')[1];
          if (!/\..*?$/i.test(newFile.name)) {
            // 无扩展名
            newFile.name = newFile.name +  "." + ext;
          }
        }
      }
    },
    inputFile(newFile, oldFile) {
      var vm = this;
      if (newFile && !oldFile) {
        newFile.data.directory = vm.directory;
      }
      if (newFile && oldFile) {
        // 更新文件


        // 开始上传
        if (newFile.active !== oldFile.active) {
          // console.log('Start upload', newFile.active, newFile);
        }

        // 上传进度
        if (newFile.progress !== oldFile.progress) {
          
        }

        // 上传错误
        if (newFile.error !== oldFile.error) {
          
        }

        // 上传成功
        if (newFile.success !== oldFile.success) {
          vm.successCount++;
        }
      }
    },
    close() {
      var files = this.files.filter(x => x.success);
      this.successCount && this.$emit('success', files);
      this.successCount && this.callback(files);
      this.$emit('close');
    }
  },

  mounted() {
    var vm = this;
    Scrollbar.init(vm.$el.querySelector('.file-list'));
    vm.$refs.upload.$watch('active', function(val) {  
        vm.uploading = val;
    })
  },
  destroyed() {
    // console.log('file-list destroyed');
    Scrollbar.destroy(this.$el.querySelector('.file-list'));
  }
}
</script>

<style type="text/css">
.file-list {
  max-height: 70vh;
}

.progress-container {
  width: 100px;
  height: 7px;
  border-radius: 8px;
  background: #eee;
  border: 1px solid #d9d9d9;
  overflow: hidden;
}
.progress-container>div {
  width: 0;
  height: 100%;
  transition: all .3s;
}

.file-name-editor {

}

.drop-tip {
  height: 250px;
  text-align: center;
  white-space: nowrap;
  overflow: hidden;
  transition: background .5s;
}

.drop-tip.full {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: .9;
}

.drop-tip.full::before {
  content: "释放鼠标以选择文件";
}

.drop-tip::before {
  content: "可拖放图片文件或文件夹至此";
  display: inline-block;
  vertical-align: middle;
  color: white;
}

.drop-tip::after {
  content: "";
  width: 0;
  height: 100%;
  display: inline-block;
  vertical-align: middle;
}

</style>